import React, { useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { ScreenshotsContext } from './Screenshot'
interface IProps {}
export default (props: IProps) => {
    const context = useContext(ScreenshotsContext);
    const { state, dispatch } = context
    const magnifyRef = useRef<HTMLCanvasElement>(null);
    const [magnifyState, setMagnifyState] = useState({ width: 120, height: 90, rgb: '' });
    const [explain, setExplain] = useState({ width: 120, height: 40 });
    const magnifyRate = useRef(4).current;

    const draw = useCallback(() => {
        const { image, viewer, magnifyPoint, width, height } = state;
        const { x, y } = magnifyPoint;
        if (!image?.el || x < 0 || y < 0 || (viewer && !viewer.resizing)) return;
        const magnifyX = (image.width * x) / width;
        const magnifyY = (image.height * y) / height;
        const magnifyW = magnifyState.width;
        const magnifyH = magnifyState.height;
        const ctx = magnifyRef.current?.getContext('2d') as CanvasRenderingContext2D;
        const colorData = ctx.getImageData(magnifyW / 2, magnifyH / 2, 1, 1).data;

        ctx.clearRect(0, 0, magnifyW, magnifyH);
        ctx.drawImage(
            image.el,
            magnifyX - magnifyW / magnifyRate / 2,
            magnifyY - magnifyH / magnifyRate / 2,
            magnifyW / magnifyRate,
            magnifyH / magnifyRate,
            0,
            0,
            magnifyW,
            magnifyH,
        );
    }, [state, magnifyRate, magnifyState]);

    useLayoutEffect(() => {
        draw();
    }, [draw]);

    const magnifyStyle = useMemo(() => {
        const bias = 5
        const { width, height, rgb } = magnifyState
        const { x, y, right, bottom } = state.magnifyPoint
        const result = {
            left: x + width + bias >= right ? x - width - bias : x + bias,
            top: y + height + explain.height + bias >= bottom ? y - height - explain.height - bias : y + bias
        }
        return result
    }, [magnifyState, state, explain])
    
    return (
        <div
            className="screenshots-magnifier"
            style={{
                transform: `translate(${magnifyStyle.left}px, ${magnifyStyle.top}px)`,
            }}
        >
            <div className="screenshots-magnifier-canvas" style={{ display: 'none'}}>
                <canvas ref={magnifyRef} width={magnifyState.width} height={magnifyState.height} />
                <div className="screenshots-magnifier-canvas-crosshair" />
            </div>
            <div className="screenshots-magnifier-explain">
                <div className="screenshots-magnifier-explain-site">
                    坐标：({state.magnifyPoint.x},{state.magnifyPoint.y})
                </div>
            </div>
        </div>
    );
};
